#!/bin/bash
#
# Developed by Fred Weinhaus 2/25/2013 .......... revised 8/12/2015
#
# ------------------------------------------------------------------------------
# 
# Licensing:
# 
# Copyright © Fred Weinhaus
# 
# My scripts are available free of charge for non-commercial use, ONLY.
# 
# For use of my scripts in commercial (for-profit) environments or 
# non-free applications, please contact me (Fred Weinhaus) for 
# licensing arrangements. My email address is fmw at alink dot net.
# 
# If you: 1) redistribute, 2) incorporate any of these scripts into other 
# free applications or 3) reprogram them in another scripting language, 
# then you must contact me for permission, especially if the result might 
# be used in a commercial or for-profit environment.
# 
# My scripts are also subject, in a subordinate manner, to the ImageMagick 
# license, which can be found at: http://www.imagemagick.org/script/license.php
# 
# ------------------------------------------------------------------------------
# 
####
#
# USAGE: vintage3 [-H tinthue] [-S tintsaturation] [-A tintamount] 
# [-b brightness] [-c contrast] [-s vignetteshape] [-r vignetterounding] 
# [-l vignettelighten] [-N noiseamount] [-L verticallines] [-B verticalbands] 
# [-S backgroundmix] [-T bordertype] [-W borderwidth] [ -R borderrounding] 
# [-C bordercolor] infile [backgroundfile] outfile 
# 
# USAGE: vintage3 [-help]
# 
# OPTIONS:
#
# -H     tinthue              vintage tint hue; 0<=integer<=360; default=32
# -S     tintsaturation       vintage tint saturation; 0<=integer<=100; 
#                             default=25
# -A     tintamount           vintage tint amount; 0<=integer<=100; default=100
# -b     brightness           vintage brightness; -100<=integer<=100; 
#                             default=10
# -c     contrast             vintage contrast; -100<=integer<=100; 
#                             default=-20
# -s     vignetteshape        vignette shape; choices are: roundrectangle, 
#                             horizontal, vertical or none; 
#                             default=roundrectangle
# -r     vignetterounding     vignette rounding percent for roundrectangle  
#                             only; 0<=integer<=50; default=50 for 
#                             roundrectangle and default=20 otherwise
# -l     vignettelighten      vignette ligntening; 0<=integer<=100; default=0
# -N     noiseamount          noise amount; 0<=integer<=100; default=40 
# -L     verticallines        intensity of vertical lines; 0<=integer<=100; 
#                             default=65 
# -B     verticalbands        intensity of vertical bands;  0<=integer<=100; 
#                             default=30 
# -M     backgroundmix        background mixing; 0<=integer<=100; 
#                             default=100
# -T     bordertype           border type; choices are: none, torn, rounded; 
#                             default=none
# -W     borderwidth          border width only for bordertype=torn or rounded; 
#                             integer>=0; default=5
# -R     borderrounding       border rounding percent only for 
#                             bordertype=rounded; 0<=integer<=50; default=10
# -C     bordercolor          border color; default=white
# 
# The backgroundfile is any texture image that is as large or larger than 
# the image to be processed. Typically the backgroundfile should be converted 
# to grayscale before using.
# 
###
# 
# NAME: VINTAGE3 
# 
# PURPOSE: To apply an old, heritage style vintage effect to an image.
# 
# DESCRIPTION: VINTAGE1 applies an old, heritage style vintage effect to an 
# image. The vintage effect includes: tint hue, tint amount, noise, lines, 
# various vignette types and various border types.
# 
# 
# ARGUMENTS: 
# 
# -H tinthue ... TINTHUE is the vintage tint hue. Values are integers between 
# 0 and 360. The default=32.
# 
# -S tintsaturation ... TINTSATURATION is the vintage tint saturation. Values 
# are integers between 0 and 100. The default=25.
# 
# -A tintamount ... TINTAMOUNT is the vintage tint amount. Values are integers 
# between 0 and 100. The default=100.
# 
# -b brightness ... BRIGHTNESS is the vintage brightness. Values are integers 
# between -100 and 100. The default=0.
# 
# -c contrast ... CONTRAST is the vintage contrast. Values are integers 
# between -100 and 100. The default=0.
# 
# -s vignetteshape ... VIGNETTESHAPE is the vignette shape. Choices are: 
# roundrectangle (r), horizontal (h), vertical (v) or none (n). The 
# default=roundrectangle.
# 
# -r vignetterounding ... VIGNETTEROUNDING is the vignette rounding percent 
# for the roundrectangle shape only. Values are integers between 0 and 50. 
# The default=20.
# 
# -l vignettelighten ... VIGNETTELIGHTEN is the vignette ligntening. Values 
# are integers between 0 and 100. The default=0.
# 
# -N noiseamt ... NOISEAMT is the amount of noise added. Values are integers 
# between 0 and 100. The default=40.
# 
# -L verticallines ... VERTICALLINES is the intensity of vertical lines added. 
# Values are integers between 0 and 100. The default=65.
# 
# -B verticalbands ... VERTICALBANDS is the intensity of vertical bands added. 
# Values are integers between 0 and 100. The default=30.
# 
# -M backgroundmix ... BACKGROUNDMIX is the amount of background mixing with 
# the image. Values are integers between 0 and 100. The default=65.
# 
# -T bordertype ... BORDERTYPE is the image border type. The choices are: 
# none (n), torn (t) or rounded (r). The default=none.
# 
# -W borderwidth ... BORDERWIDTH is the image border width only for 
# bordertype=torn or rounded. Values are integers between 0 and 100. 
# The default=5.
# 
# -R borderrounding ... BORDERROUNDING is the image border rounding percent 
# only for bordertype=rounded.  Values are integers between 0 and 50. The 
# default=10. 
# 
# -C bordercolor ... BORDERCOLOR is the image border color. Any valid IM color 
# is allowed. The default=white.
# 
# REFERENCES:
# http://www.photoshop-plus.co.uk/2011/03/15/vintage-photo-effects-using-adobe-photoshop/
# http://aceinfowayindia.com/blog/2009/12/how-to-create-vintage-photo-effect-photoshop-tutorial/
# 
# BACKGROUNDS:
# http://www.flickr.com/photos/borealnz/sets/72157610307314214/with/3495540187/
# --- http://www.flickr.com/photos/borealnz/3495540187/in/set-72157610307314214
# --- http://www.flickr.com/photos/borealnz/3124030212/in/set-72157610307314214
# http://lostandtaken.com/
# --- http://www.unsigneddesign.com/LT_AntiquePaper.zip
# --- http://www.unsigneddesign.com/LT_MicroscopicGrit.zip
# 
# CAVEAT: No guarantee that this script will work on all platforms, 
# nor that trapping of inconsistent parameters is complete and 
# foolproof. Use At Your Own Risk. 
# 
######
# 

# set default values

# primary parameters
tinthue=32
tintsaturation=25
tintamt=100
brightness=0
contrast=0
vignetteshape="roundrectangle"
vignetterounding=20
vignettelighten=0
noiseamt=40
verticalnoiseamt=65
bandingamt=30
backgroundamt=65
bordertype="none"
bordercolor="white"
borderwidth=5
borderrounding=10


# ancillary
tintlightness=50
bandingwidth=15
vignettesize=85
noiseseed=100
vertnoiseseed=100
bandseed=40
vignettesaturation=81
vignettelightness=34
torndensity=1
torncurviness=5
tornroughness=1
tornpad=2
tornseed=100

# set directory for temporary files
dir="."    # suggestions are dir="." or dir="/tmp"

# set up functions to report Usage and Usage with Description
PROGNAME=`type $0 | awk '{print $3}'`  # search for executable on path
PROGDIR=`dirname $PROGNAME`            # extract directory of program
PROGNAME=`basename $PROGNAME`          # base name of program
usage1() 
	{
	echo >&2 ""
	echo >&2 "$PROGNAME:" "$@"
	sed >&2 -e '1,/^####/d;  /^###/g;  /^#/!q;  s/^#//;  s/^ //;  4,$p' "$PROGDIR/$PROGNAME"
	}
usage2() 
	{
	echo >&2 ""
	echo >&2 "$PROGNAME:" "$@"
	sed >&2 -e '1,/^####/d;  /^######/g;  /^#/!q;  s/^#*//;  s/^ //;  4,$p' "$PROGDIR/$PROGNAME"
	}


# function to report error messages
errMsg()
	{
	echo ""
	echo $1
	echo ""
	usage1
	exit 1
	}


# function to test for minus at start of value of second part of option 1 or 2
checkMinus()
	{
	test=`echo "$1" | grep -c '^-.*$'`   # returns 1 if match; 0 otherwise
    [ $test -eq 1 ] && errMsg "$errorMsg"
	}

# test for correct number of arguments and get values
if [ $# -eq 0 ]
	then
	# help information
   echo ""
   usage2
   exit 0
elif [ $# -gt 35 ]
	then
	errMsg "--- TOO MANY ARGUMENTS WERE PROVIDED ---"
else
	while [ $# -gt 0 ]
		do
			# get parameter values
			case "$1" in
		     -help)    # help information
					   echo ""
					   usage2
					   exit 0
					   ;;
				-H)    # get tinthue
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID TINTHUE SPECIFICATION ---"
					   checkMinus "$1"
					   tinthue=`expr "$1" : '\([0-9]*\)'`
					   [ "$tinthue" = "" ] && errMsg "--- TINTHUE=$tinthue MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$tinthue < 0" | bc`
					   test2=`echo "$tinthue > 360" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- TINTHUE=$tinthue MUST BE AN INTEGER BETWEEN 0 AND 360 ---"
					   ;;
				-S)    # get tintsaturation
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID TINTSATURATION SPECIFICATION ---"
					   checkMinus "$1"
					   tintsaturation=`expr "$1" : '\([0-9]*\)'`
					   [ "$tintsaturation" = "" ] && errMsg "--- TINTSATURATION=$tintsaturation MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$tintsaturation < 0" | bc`
					   test2=`echo "$tintsaturation > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- TINTSATURATION=$tintsaturation MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				-A)    # get tintamt
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID TINTAMOUNT SPECIFICATION ---"
					   checkMinus "$1"
					   tintamt=`expr "$1" : '\([0-9]*\)'`
					   [ "$tintamt" = "" ] && errMsg "--- TINTAMOUNT=$tintamt MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$tintamt < 0" | bc`
					   test2=`echo "$tintamt > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- TINTAMOUNT=$tintamt MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				-b)    # get brightness
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID BRIGHTNESS SPECIFICATION ---"
					   #checkMinus "$1"
					   brightness=`expr "$1" : '\([-0-9]*\)'`
					   [ "$brightness" = "" ] && errMsg "--- BRIGHTNESS=$brightness MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$brightness < -100" | bc`
					   test2=`echo "$brightness > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- BRIGHTNESS=$brightness MUST BE AN INTEGER BETWEEN -100 AND 100 ---"
					   ;;
				-c)    # get contrast
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID CONTRAST SPECIFICATION ---"
					   #checkMinus "$1"
					   contrast=`expr "$1" : '\([-0-9]*\)'`
					   [ "$contrast" = "" ] && errMsg "--- CONTRAST=$contrast MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$contrast < -100" | bc`
					   test2=`echo "$contrast > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- CONTRAST=$contrast MUST BE AN INTEGER BETWEEN -100 AND 100 ---"
					   ;;
				-s)    # get  vignetteshape
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID VIGNETTESHAPE SPECIFICATION ---"
					   checkMinus "$1"
					   vignetteshape=`echo "$1" | tr '[A-Z]' '[a-z]'`
					   case "$vignetteshape" in 
					   		roundrectangle|r) vignetteshape=roundrectangle ;;
					   		horizontal|h) vignetteshape=horizontal;;
					   		vertical|v) vignetteshape=vertical;;
					   		none|n) vignetteshape=none;;
					   		*) errMsg "--- VIGNETTESHAPE=$vignetteshape IS AN INVALID VALUE ---"  ;;
					   esac
					   ;;
				-r)    # get vignetterounding
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID VIGNETTEROUNDING SPECIFICATION ---"
					   checkMinus "$1"
					   vignetterounding=`expr "$1" : '\([0-9]*\)'`
					   [ "$vignetterounding" = "" ] && errMsg "--- VIGNETTEROUNDING=$vignetterounding MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$vignetterounding < 0" | bc`
					   test2=`echo "$vignetterounding > 50" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- VIGNETTEROUNDING=$vignetterounding MUST BE AN INTEGER BETWEEN 0 AND 50 ---"
					   ;;
				-l)    # get vignettelighten
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID VIGNETTELIGHTEN SPECIFICATION ---"
					   checkMinus "$1"
					   vignettelighten=`expr "$1" : '\([0-9]*\)'`
					   [ "$vignettelighten" = "" ] && errMsg "--- VIGNETTELIGHTEN=$vignettelighten MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$vignettelighten < 0" | bc`
					   test2=`echo "$vignettelighten > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- VIGNETTELIGHTEN=$vignettelighten MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				-N)    # get noiseamt
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID NOISEAMOUNT SPECIFICATION ---"
					   checkMinus "$1"
					   noiseamt=`expr "$1" : '\([0-9]*\)'`
					   [ "$noiseamt" = "" ] && errMsg "--- NOISEAMOUNT=$noiseamt MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$noiseamt < 0" | bc`
					   test2=`echo "$noiseamt > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- NOISEAMOUNT=$noiseamt MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				-L)    # get verticalnoiseamt
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID VERTICALLINES SPECIFICATION ---"
					   checkMinus "$1"
					   verticalnoiseamt=`expr "$1" : '\([0-9]*\)'`
					   [ "$verticalnoiseamt" = "" ] && errMsg "--- VERTICALLINES=$verticalnoiseamt MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$verticalnoiseamt < 0" | bc`
					   test2=`echo "$verticalnoiseamt > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- VERTICALLINES=$verticalnoiseamt MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				-B)    # get bandingamt
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID VERTICALBANDS SPECIFICATION ---"
					   checkMinus "$1"
					   bandingamt=`expr "$1" : '\([0-9]*\)'`
					   [ "$bandingamt" = "" ] && errMsg "--- VERTICALBANDS=$bandingamt MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$bandingamt < 0" | bc`
					   test2=`echo "$bandingamt > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- VERTICALBANDS=$bandingamt MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				-M)    # get backgroundamt
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID BACKGROUNDMIX SPECIFICATION ---"
					   checkMinus "$1"
					   backgroundamt=`expr "$1" : '\([0-9]*\)'`
					   [ "$backgroundamt" = "" ] && errMsg "--- BACKGROUNDMIX=$backgroundamt MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$backgroundamt < 0" | bc`
					   test2=`echo "$backgroundamt > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- BACKGROUNDMIX=$backgroundamt MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				-T)    # get  bordertype
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID BORDERTYPE SPECIFICATION ---"
					   checkMinus "$1"
					   bordertype=`echo "$1" | tr '[A-Z]' '[a-z]'`
					   case "$bordertype" in 
					   		none|n) bordertype=none ;;
					   		torn|t) bordertype=torn;;
					   		round|rounded|r) bordertype=round;;
					   		*) errMsg "--- BORDERTYPE=$bordertype IS AN INVALID VALUE ---"  ;;
					   esac
					   ;;
				-W)    # get borderwidth
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID BORDERWIDTH SPECIFICATION ---"
					   checkMinus "$1"
					   borderwidth=`expr "$1" : '\([0-9]*\)'`
					   [ "$borderwidth" = "" ] && errMsg "--- BORDERWIDTH=$borderwidth MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$borderwidth < 0" | bc`
					   test2=`echo "$borderwidth > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- BORDERWIDTH=$borderwidth MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				-R)    # get borderrounding
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID BORDERROUNDING SPECIFICATION ---"
					   checkMinus "$1"
					   borderrounding=`expr "$1" : '\([0-9]*\)'`
					   [ "$borderrounding" = "" ] && errMsg "--- BORDERROUNDING=$borderrounding MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$borderrounding < 0" | bc`
					   test2=`echo "$borderrounding > 50" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- BORDERROUNDING=$borderrounding MUST BE AN INTEGER BETWEEN 0 AND 50 ---"
					   ;;
				-C)    # get bordercolor
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID BORDERCOLOR SPECIFICATION ---"
					   checkMinus "$1"
					   bordercolor="$1"
					   ;;
				 -)    # STDIN and end of arguments
					   break
					   ;;
				-*)    # any other - argument
					   errMsg "--- UNKNOWN OPTION ---"
					   ;;
		     	 *)    # end of arguments
					   break
					   ;;
			esac
			shift   # next option
	done
	#
	# get infile and outfile
	if [ $# -eq 3 ]; then
		infile="$1"
		backgroundfile="$2"
		outfile="$3"
	elif [ $# -eq 2 ]; then
		infile="$1"
		outfile="$2"
		backgroundfile=""
	else
		backgroundfile=""
	fi
fi

# test that infile provided
[ "$infile" = "" ] && errMsg "NO INPUT FILE SPECIFIED"

# test that outfile provided
[ "$outfile" = "" ] && errMsg "NO OUTPUT FILE SPECIFIED"

# setup temp files
tmpA1="$dir/vintage3_1_$$.mpc"
tmpB1="$dir/vintage3_1_$$.cache"
tmpA2="$dir/vintage3_2_$$.mpc"
tmpB2="$dir/vintage3_2_$$.cache"
trap "rm -f $tmpA1 $tmpB1 $tmpA2 $tmpB2;" 0
trap "rm -f $tmpA1 $tmpB1 $tmpA2 $tmpB2; exit 1" 1 2 3 15
trap "rm -f $tmpA1 $tmpB1 $tmpA2 $tmpB2; exit 1" ERR

# get im_version
im_version=`convert -list configure | \
	sed '/^LIB_VERSION_NUMBER */!d; s//,/;  s/,/,0/g;  s/,0*\([0-9][0-9]\)/\1/g' | head -n 1`

# colorspace RGB and sRGB swapped between 6.7.5.5 and 6.7.6.7 
# though probably not resolved until the latter
# then -colorspace gray changed to linear between 6.7.6.7 and 6.7.8.2 
# then -separate converted to linear gray channels between 6.7.6.7 and 6.7.8.2,
# though probably not resolved until the latter
# so -colorspace HSL/HSB -separate and -colorspace gray became linear
# but we need to use -set colorspace RGB before using them at appropriate times
# so that results stay as in original script
# The following was determined from various version tests using vintage3
# with IM 6.7.4.10, 6.7.6.10, 6.8.3.3, 6.8.3.8 6.8.3.9 6.8.4.3 6.8.4.6
# note: some odd problems with -set colorspace required some different processing as noted below
if [ "$im_version" -lt "06070607" -o "$im_version" -gt "06070707" ]; then
	setcspace="-set colorspace RGB"
else
	setcspace=""
fi
# no need for setcspace for grayscale or channels after 6.8.5.4
# but to keep the same look, must use colorspace rec601luma via -intensity, since now colorspace gray is rec709luma
# also correct for -tint
if [ "$im_version" -gt "06080504" ]; then
	setcspace="-intensity rec601luma"
	setcspace2="-set colorspace sRGB"
	graycorrect="-intensity rec601luma"
else
	setcspace=""
	setcspace2=""
	graycorrect=""
fi


# test input image
convert -quiet "$infile" -auto-level +repage "$tmpA1" ||
	errMsg "--- FILE $infile DOES NOT EXIST OR IS NOT AN ORDINARY FILE, NOT READABLE OR HAS ZERO SIZE ---"

ww=`identify -ping -format "%w" $tmpA1`
hh=`identify -ping -format "%h" $tmpA1`
mindim=`convert xc: -format "%[fx:min($ww,$hh)]" info:`


if [ "$backgroundfile" != "" ]; then
	convert -quiet -regard-warnings "$backgroundfile" +repage "$tmpA2" ||
		errMsg "--- FILE $backgroundfile DOES NOT EXIST OR IS NOT AN ORDINARY FILE, NOT READABLE OR HAS ZERO SIZE ---"
fi


# convert to grayscale
# note: from vintage1 and vintage2, we need to feed the noise processing a non-linear gray image
convert $tmpA1 $setcspace -colorspace gray -set colorspace sRGB $tmpA1


# add noise
if [ "$noiseamt" != "0" ]; then
	noiseamt=`convert xc: -format "%[fx:$noiseamt/100]" info:`
	# need to add -set colorspace sRGB at end (not $setcspace as it causes imo results to be grayscale)
	# for the next two sections regarding adding noise and vertical noise to work correctly -- very strange
	# this changed between 6.8.3.8 and 6.8.3.9
	# due to changes in -colorspace gray when -intensity was being introduced and debugged
	convert $tmpA1 -seed $noiseseed -attenuate $noiseamt +noise gaussian $setcspace -colorspace gray -set colorspace sRGB $tmpA1
fi

# add vertical noise
if [ "$verticalnoiseamt" != "0" ]; then
	# note need to use non-linear (rather than linear) gray image to avoid 
	# (bug driven) lower contrast results from versions 6.8.3.10 through 6.8.4.4
	# could have used gray50, but decided to keep gray(50%) and add -colorspoce sRGB
	# which does not seem to alter results prior to 6.7.7.7
	convert $tmpA1 \
		\( -size ${ww}x1 xc:"gray(50%)" $setcspace2 \
			-seed $vertnoiseseed -attenuate 15 +noise uniform \
			$setcspace -colorspace gray -resize ${ww}x${hh}\! \
			-alpha set -channel A -evaluate set $verticalnoiseamt% +channel \) \
		-compose overlay -composite \
	$tmpA1
fi

# add banding
if [ "$bandingamt" != "0" ]; then
	convert $tmpA1 \
		\( -size ${ww}x1 -seed $bandseed plasma:fractal \
			$setcspace -colorspace gray -blur 0x$bandingwidth -resize ${ww}x${hh}\! \
			-auto-level -alpha set -channel A -evaluate set $bandingamt% +channel \) \
		-compose overlay -composite \
	$tmpA1
fi
	
	
# add background image
if [ "$backgroundfile" != "" ]; then
	convert $tmpA1 \
		\( $tmpA2 -resize ${ww}x${hh}\! -alpha set -channel A -evaluate set $backgroundamt% +channel \) \
		-compose overlay -composite \
	$tmpA1
fi

# process for color change
# note tintcolor needs -colorspace sRGB to make imo, im6 and im produce same colors
tinthue=`convert xc: -format "%[fx:$tinthue*100/360]" info:`
tintcolor=`convert -size 1x1 xc:"hsl($tinthue%,$tintsaturation%,$tintlightness%)" -colorspace sRGB -format "%[pixel:u.p{0,0}]" info:`
convert $tmpA1 $setcspace \
	\( -clone 0 -fill "$tintcolor" $graycorrect -tint 100% \
		-alpha set -channel A -evaluate set $tintamt% +channel \) \
	-compose over -composite -brightness-contrast ${brightness}x${contrast} \
	$tmpA1


# setup vignette
if [ "$vignetteshape" = "vertical" ]; then
	convert -size ${ww}x${hh} xc:black -crop 100x${vignettesize}+0+0% +repage \
		-background white -gravity center -extent ${ww}x${hh} \
		-morphology distance euclidean:4 -auto-level -negate $tmpA2
elif [ "$vignetteshape" = "horizontal" ]; then
	convert -size ${ww}x${hh} xc:black -crop ${vignettesize}x100+0+0% +repage \
		-background white -gravity center -extent ${ww}x${hh} \
		-morphology distance euclidean:4 -auto-level -negate $tmpA2
elif [ "$vignetteshape" = "roundrectangle" ]; then
	xc=`convert xc: -format "%[fx:$ww/2]" info:`
	yc=`convert xc: -format "%[fx:$hh/2]" info:`
	ww2=`convert xc: -format "%[fx:($vignettesize/100)*($ww/2)]" info:`
	hh2=`convert xc: -format "%[fx:($vignettesize/100)*($hh/2)]" info:`
	round=`convert xc: -format "%[fx:min($ww,$hh)*$vignetterounding/100]" info:`
	args="-$ww2,-$hh2 $ww2,$hh2 $round,$round"
	convert -size ${ww}x${hh} xc:white -fill black \
		-draw "translate $xc,$yc roundrectangle $args" -alpha off \
		-morphology Distance Euclidean:4 -auto-level -negate $tmpA2
fi


# add vignette
if [ "$vignetteshape" != "none" ]; then
	vignettecolor=`convert -size 1x1 xc:"hsl($tinthue%,$vignettesaturation%,$vignettelightness%)" $setcspace -format "%[pixel:u.p{0,0}]" info:`
	convert $tmpA1 \
		\( $tmpA2 +level-colors "$vignettecolor,white" +level ${vignettelighten}x100% -blur 0x5 \) \
		-compose multiply -composite $tmpA1
fi


# add border/frame
if [ "$bordertype" = "torn" ]; then
	psize=$((borderwidth+tornpad))
	# see disperse script
		# create bordercolor image for compositing at the end
		# create white image with black around the inside of the edges
		# create random image, blur, apply sin/cos to RG channel (for GB) and previous image (for R), displace around border, add slight spread for tornroughness
		# composite backgroundcolor original image and dispersed border
	convert $tmpA1 \
		\( -clone 0 -fill "$bordercolor" -colorize 100% \) \
		\( -clone 0 -fill white -colorize 100% -shave ${psize}x${psize} -bordercolor black -border $psize \) \
		\( -clone 0 -seed $tornseed +noise Random -blur 0x$torncurviness \
			$setcspace -colorspace gray -auto-level $setcspace2 \
			-channel R -evaluate sine $torndensity \
			-channel G -evaluate cosine $torndensity \
			-channel RG -separate -clone 2 -insert 0 \
			-define compose:args=${borderwidth}x${borderwidth} \
			-compose displace -composite -interpolate bilinear -spread $tornroughness -blur 0x0.7 \) \
		-delete 2 -swap 0,1 -compose over -composite -trim +repage \
		-gravity center -background "$bordercolor" -extent ${ww}x${hh} \
		$tmpA1

elif [ "$bordertype" = "round" ]; then
	# need special processing for IM before 6.7.6.8 to set up the alpha channel so that it is white before addding black cornerss 
	if [ "$im_version" -lt "06070608" ]; then
		# either of the following work
		# aproc="-matte -channel A -evaluate set 0%"
		aproc="+matte -channel A -evaluate set 100%"
	else
		aproc="-alpha set -channel A"
	fi
	round=`convert xc: -format "%[fx:min($ww,$hh)*$borderrounding/100]" info:`
	convert $tmpA1 \( -clone 0 $aproc -separate +channel \
		\( -size ${round}x${round} xc:black -draw "fill white circle ${round},${round} ${round},0" -alpha off -write mpr:arc +delete \) \
		\( mpr:arc \) -gravity northwest -composite \
		\( mpr:arc -flip \) -gravity southwest -composite \
		\( mpr:arc -flop \) -gravity northeast -composite \
		\( mpr:arc -rotate 180 \) -gravity southeast -composite \) \
		\( -clone 0 -clone 1 -alpha off -compose copy_opacity -composite \
		-background "$bordercolor" -compose over -flatten \
		-compose over -bordercolor "$bordercolor" -border $borderwidth \) \
		-delete 0,1 $tmpA1

fi


convert $tmpA1 "$outfile"

exit 0
